<template>
	<div class="userInfo">
		<van-form ref="form" @submit="onSubmit">
			<van-cell-group inset>
				<van-field
					v-if="formList.maskNameFlag"
					v-model="formList.name"
					name="name"
					label="姓名"
					placeholder="姓名"
					maxlength="80"
					:rules="[{ required: true, message: '姓名必填' }]"
					/>
					<!-- :disabled="userInfo?.documentName" -->
				<van-field
					v-if="!formList.maskNameFlag"
					v-model="formList.showName"
					name="name"
					label="姓名"
					placeholder="姓名"
					maxlength="80"
					:disabled="userInfo?.documentName"
					:rules="[{ required: true, message: '姓名必填' }]"
				/>
				<van-field
					v-model="formList.idType"
					name="证件类型"
					label="证件类型"
					placeholder="证件类型"
					disabled
				/>
				<van-field
					v-if="formList.maskIdFlag"
					v-model="formList.id"
					name="idRules"
					label="证件号"
					placeholder="证件号"
					maxlength="50"
					:rules="[
						{ required: true, message: '证件号必填' },
						{ validator: validatorId, message: '证件号填写有误' },
					]"
				/>
				<!-- :disabled="!!proUserInfo?.documentNo" -->
				<van-field
					v-if="!formList.maskIdFlag"
					v-model="formList.showId"
					name="idRules"
					label="证件号"
					placeholder="证件号"
					maxlength="50"
					@focus="formList.maskIdFlag = !formList.maskIdFlag"
					:rules="[{ required: true, message: '证件号必填' }]"
					/>
					<!-- :disabled="!!proUserInfo?.documentNo" -->
					<van-field
					v-if="formList.maskMobileFlag"
					v-model="formList.mobile"
					name="telRules"
					label="手机号码"
					type="tel"
					placeholder="请输入手机号码"
					maxlength="11"
					:disabled="!!proUserInfo?.mobileNo"
					:rules="[
						{ required: true, message: '手机号码必填' },
						{ validator, message: '手机号填写有误' },
					]"
					@update:modelValue="telInput"
				/>
				<van-field
					v-if="!formList.maskMobileFlag"
					v-model="formList.showMobile"
					name="telRules"
					label="手机号码"
					type="tel"
					@focus="formList.maskMobileFlag = !formList.maskMobileFlag"
					placeholder="手机号码"
					maxlength="11"
					:disabled="!!proUserInfo?.mobileNo"
					:rules="[{ required: true, message: '手机号码必填' }]"
					@update:modelValue="telInput"
				/>
				<div class="code_div">
					<van-field
						v-model="formList.smsCode"
						name="codeRules"
						label="验证码"
						class="code_input"
						placeholder="请输入验证码"
						autocomplete="off"
						maxlength="6"
						:rules="[
							{ required: true, message: '请输入验证码' },
							{
								validator: validatorCode,
								message: '请输入正确的验证码',
							},
						]"
						@update:modelValue="codeInput"
					/>
					<van-button
						square
						plain
						:loading="loading"
						type="primary"
						loading-type="spinner"
						class="sendButton"
						:text="codeTextflag"
						@click.prevent="sendCodeBtn"
					/>
				</div>
			</van-cell-group>
			<div class="hint"><van-icon name="warning" /><span class="textRight">请务必填写您本人使用的手机号码。</span></div>
			<div style="margin: 16px">
				<van-button
					v-log-button-name="'保单检视_个人信息确认_下一步'"
					class="primaryButton"
					square
					block
					type="primary"
					:loading="subLoading"
					loading-type="spinner"
					native-type="submit"
					text="下一步"
				/>
			</div>
		</van-form>
	</div>
</template>
<script lang="ts" setup>
import {
	regPhoneTest,
	regTypeCodeTest,
	submitForm,
} from '/@/utils/Verification'
import { userSubmit, sendSms, subCode } from '/@/api/index'
import { Dialog, Toast } from '/@/utils/Message'
import { userInfoStrore } from '/@/stores/userInfoStore'
import { policyListStore } from '/@/stores/policyListStore'
import { useRouter, onBeforeRouteLeave } from 'vue-router'
import { sm2 } from 'sm-crypto'
import { ref, reactive, onMounted,watch } from 'vue'
import { createCustomMark } from '/@/api/auth/repot'
import { log } from 'console'
//公钥串---加密使用
const publicKey = ref<string>(
	'044291b381a039a8d7d02d7272d2d7c78a30d33e3eeaa0b509bf77d2376582ab2d573730e6bfe9a53bad53f53ac1a85d9c11050931f04bc8b3afc04144d5a6f9be'
)
//私钥串---解密使用
const privateKey = ref<string>(
	'5aa03412c3051e1d4cf9d19cfbeeec70c28f388c9f82747cc912096c9cd44bea'
)
// 加密方法
const JIAMIPublicData = (data): string => {
	const cipherMode = 1
	const result = sm2.doEncrypt(data, publicKey.value, cipherMode)
	return `04${result}`
}
// 解密方法
const JIMIPublicData = (data: any): string => {
	const cipherMode = 1
	//data为加密的数据
	const result = sm2.doDecrypt(
		data.substring(2),
		privateKey.value,
		cipherMode
	)
	return result
}
const props = defineProps({
	agreementTitle1: {
		// 用户协议
		default: '',
		type: String,
	},
	agreementTitle2: {
		// 个人隐私政策
		default: '',
		type: String,
	},
})
const router = useRouter()
const form = ref(null) as any
const codeTextflag = ref('获取验证码')
const isSendCode = ref(false)
let timer
let userInfo = store.userInfoObj as any
let proUserInfo = store.proWritingUsetInfo as any
const pStore = policyListStore()
function maskName(str: any) {
	if (null != str && str != undefined) {
		let star = '' //存放名字中间的* //名字是两位的就取姓名首位+*
		if (str.length <= 2) {
			return '*' + str.substring(1, 2)
		} else {
			for (var i = 0; i < str.length - 2; i++) {
				star = star + '*'
			}
			return (
				str.substring(0, 1) +
				star +
				str.substring(str.length - 1, str.length)
			)
		}
	}
}
function maskId(str: any) {
	if (null != str && str != undefined) {
		let star = ''
		for (var i = 0; i < str.length - 4; i++) {
			star = star + '*'
		}
		return star + str.substring(str.length - 4, str.length)
	}
}
function maskmobile(str: any) {
	if (null != str && str != undefined) {
		let star = ''
		for (var i = 0; i < str.length - 7; i++) {
			star = star + '*'
		}
		return (
			str.substring(0, 3) +
			star +
			str.substring(str.length - 4, str.length)
		)
	}
}
const formList = reactive({
	name: proUserInfo?.documentName,
	showName: maskName(proUserInfo?.documentName),
	maskNameFlag: !!proUserInfo?.documentName ? false : true,
	idType: '身份证',
	id: proUserInfo?.documentNo,
	showId: maskId(proUserInfo?.documentNo),
	maskIdFlag: !!proUserInfo?.documentNo ? false : true,
	mobile: proUserInfo?.mobileNo,
	showMobile: maskmobile(proUserInfo?.mobileNo),
	maskMobileFlag: !!proUserInfo?.mobileNo ? false : true,
	smsCode: '',
})
watch(() => formList.id, (newVal:any, oldVal:any) => {
	formList.id = newVal.toUpperCase()
})
//  大写字母
// const toformList = (v:any) => {
// 	formList.id = formList.id.toUpperCase()
// }
const validator = (val: any) => {
	// 手机号的校验
	if (val != userInfo?.mobileNo) {
		if (regPhoneTest(val)) {
			formList.showMobile = maskmobile(val)
			formList.maskMobileFlag = false
		}
		return regPhoneTest(val)
	} else {
		return true
	}
}
const validatorId = (val: any) => {
	// 证件号的校验
	if (val != userInfo?.documentNo) {
		if (regTypeCodeTest(userInfo?.documentType, val)) {
			formList.showId = maskId(val)
			formList.maskIdFlag = false
		}
		return regTypeCodeTest(userInfo?.documentType, val)
	} else {
		return true
	}
}
const validatorCode = (val: any) => {
	// 验证码的校验
	return /^[0-9]{6}$/.test(val)
}
const telInput = () => {
	// 修改手机号的时候，验证码清空
	formList.smsCode = ''
}
const codeInput = async () => {
	// 先输入手机号， 然后再输入验证码
	const status = await submitForm(form, ['telRules'])
	if (status.length > 0) formList.smsCode = ''
}

const loading = ref(false)
const sendCodeBtn = async () => {
	// 点击发送验证的按钮
	if (codeTextflag.value.indexOf('验证码') <= 0) return
	const status = await submitForm(form, ['name', 'idRules', 'telRules'])
	if (status.length == 0) {
		loading.value = true
		// if(window.location.href.indexOf("reviewH5") > 0) { // 保单检视的都提交信息
		// let result = await mobileSubmit()
		// if(result) {
		sendCode()
		// }
		// }
	}
}
export interface userSaveInfo {
	documentName?: string
	mobileNo?: string
	documentNo?: string
}
const mobileSubmit = async () => {
	let obj: userSaveInfo = {}
	let newobj = { mobile: formList.mobile as string }
	let params: any = JSON.stringify(newobj)
	return new Promise((resolve, reject) => {
		userSubmit(params).then((res: any) => {
			loading.value = false
			if (res.code == 200) {
				// store.postUserInfo({...res.data,...newobj})
				store.setUserInfo(res.data)
				userInfo = store.userInfoObj as any
				let obj = {
					moblie: formList.mobile,
					...userInfo,
				}
				// formList.id = res.data.documentNo
				// formList.mobile = res.data.mobileNo
				resolve(true)
			} else {
				Dialog({
					message: res.msg || '操作错误', // '您的手机号已被占用注册，请更换手机号。'
					confirmText: '确定',
				}).then(() => {
					loading.value = false
					codeTextflag.value = '获取验证码'
				})
				reject(false)
			}
		})
	})
}
//创建唯一标识
const callbackSuccess = async () => {
	 const a =  await createCustomMark({ taskCode: pStore.taskNo })
	if (a.code == 200) {
		sessionStorage.removeItem('customToken')
		sessionStorage.setItem('customToken', a.customToken)
	}
}
const sendCode = () => {
	let obj: userSaveInfo = {}
	let newobj = { mobile: formList.mobile as string }
	let params: any = JSON.stringify(newobj)
	return new Promise((resolve, reject) => {
		userSubmit(params).then((res: any) => {
			// sendSms(store.transactionId as any).then((res:any) => {
			if (res.code == 200) {
				if (res.data.result) {
					Toast('验证码已发出')
					isSendCode.value = true
					let n = 60
					timer = setInterval(() => {
						codeTextflag.value = `${n}s`
						if (loading.value) {
							loading.value = false // 修改为点击按钮先置灰，响应成功之后开始倒计时
						}
						n--
						if (n < 0) {
							clearInterval(timer)
							codeTextflag.value = '获取验证码'
						}
					}, 1000)
				} else {
					Toast('获取验证码错误,请重新获取')
				}
			} else {
				loading.value = false
				codeTextflag.value = '获取验证码'
				Dialog({
					message: res.msg || '操作错误', // '您的手机号已被占用注册，请更换手机号。'
				})
			}
		})
	})
}
const subLoading = ref(false)
const onSubmit = async () => {
	if (!isSendCode.value) {
		Toast('请获取验证码')
		return
	}
	let isShowType = await isShowIdType()
	if (isShowType) {
		return
	}
	subLoading.value = true
	let newobj = {
		credential: formList.smsCode as any,
		mobile: formList.mobile as string,
		taskCode: userInfo.taskCode
	}
	let params: any = JSON.stringify(newobj)
	subCode(params).then(async (res: any) => {
		if (res.code == 200) {
			//验证成功创建唯一标识
			callbackSuccess()
			userInfo = store.userInfoObj as any
			let obj = {
				...userInfo,
				mobileNo: formList.mobile,
				documentName: JIAMIPublicData(formList.name),
				documentNo: JIAMIPublicData(formList.id.toUpperCase()),
			}
			store.setUserInfo(obj)
			store.postUserInfo(obj)
			if (res.data.result) {
				// 通过中转页面的letter参数判断，下一步请求成功后是否跳转到报告生成页面
			let letter = JSON.parse(
				sessionStorage.getItem('isShareObj')
			)?.letter
			if (letter == '6' || letter == '15') {
				//保持isSharObj的干净状态，不至于导致后续判断错误问题
				sessionStorage.removeItem('isShareObj')
				router.push({
					path: '/reportingResultxysc',
					query: {
						taskCode: userInfo.taskCode,
						isYsc: '1',
					},
				})
			} else if (letter == '18') {
				//保持isSharObj的干净状态，不至于导致后续判断错误问题
				sessionStorage.removeItem('isShareObj')
				router.push({
					path: '/reportingResultybc',
					query: {
						taskCode: userInfo.taskCode,
						isYsc: '1',
					},
				})
			} else{
				if (userInfo?.auth == 'FACE' ) {
					router.push({
						path: '/userValidation',
					})
				} else {
					// 跳转到success页面 存储cookie
					// router.push({
					// 	path: '/status/success',
					// })
					if (
						!!JSON.parse(sessionStorage.getItem('isShareObj'))
							?.isShare
					) {
						//保持isSharObj的干净状态，不至于导致后续判断错误问题
						sessionStorage.removeItem('isShareObj')
						router.go(-1)
					} else {
						router.push({
							path: userInfo.nexturl,
							query: {
								taskCode: userInfo.taskCode,
								face: 'true',
							},
						})
						//保持isSharObj的干净状态，不至于导致后续判断错误问题
						sessionStorage.removeItem('isShareObj')
					}
				}
			}
			} else {
				Dialog({
					message: '验证码错误,请输入正确的验证码',
				})
			}
		} else {
			Dialog({
				message: res.msg || '操作错误',
			})
		}
		subLoading.value = false
	})
}
const isShowIdType = async () => {
	let idType = userInfo?.documentType
	let editableStatusPhone = userInfo?.editableStatus?.mobileNo
	if (idType != '111' && editableStatusPhone) {
		Dialog({
			title: '提示',
			confirmText: '确定',
			message:
				'如果您的证件类型为非身份证，且尚未注册金事通，我们暂无法为您提供服务。请您下载金事通App，通过【服务】->【非中国大陆从业人员注册】完成账户注册后，再使用本功能。',
		})
		return true
	} else {
		return false
	}
}
onMounted(async () => {
	//保证每次进来 这个获取验证码的按钮都是可以点击的  不保留上次的验证码
	loading.value = false
	formList.smsCode = ""
	// formList.idType = await getIdType(userInfo?.documentType)
	isShowIdType()
})
onBeforeRouteLeave((to, form, next) => {
	if (timer) {
		clearInterval(timer)
		codeTextflag.value = '获取验证码'
	}
	next()
})
defineExpose({
	mobileSubmit,
	sendCode,
})
</script>

<style scoped>
.userInfo :deep(.van-field__control):disabled {
    -webkit-text-fill-color: #777879!important;
}
</style>
<style lang="less" scoped>
@import '/@/assets/css/vant/vantField.less';
.van-button {
	&.primaryButton {
		border-radius: 20px !important;
		height: 44px;
		width: 60%;
		margin: 0 auto;
		margin-top: 65.5px;
		background-color: #3296FA;
	}
}
.code_div {
	position: relative;
	:deep(.van-button) {
		position: absolute;
		right: 16px;
		// top: 0.6rem;
		top: 1.4rem;
		transform: translateY(-50%);
		height: 21px;
		font-size: 12px;
		border-radius: 2px;
	}
	:deep(.van-button--normal) {
		right: 0;
		width: 25%;
		height: 45.5px;
		padding: 0;
		box-sizing: border-box;
		border: 1px solid #198AFA ;
		background-color: #F3F9FF;
	}
	:deep(.van-button__text) {
		color: #13c2ed ;
	}
	:deep(.van-cell) {
		width: 70%;	
}
	:deep( .van-cell.code_input .van-cell__value ) {
		flex: 1;
}
}
:deep(.van-cell) {
	margin-bottom: 20px;
	background: #F6F9FD;
	border-radius: 4px;
}
:deep(.van-cell::after)  {
    border: none;
}
:deep(.van-field__label) {
    width: 30%;
}
:deep(.van-field__control, .t_i_r)  {
    text-align: right;
}
.hint{
	width: 100%;
	height: 24px;
	font-size: 12px;
	margin: 8px 0 0 8px;
	color:rgba(0,0,0,.6);
	.textRight{
		padding-left:8px;
	}
}
</style>
